﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using Microsoft.Research.Kinect.Nui;
using System.Reactive.Subjects;
using System.Windows.Media;
using System.Reactive.Linq;

namespace Kinect.KinectMouseControl
{
    public class ImageFrameToBitmapSourceConverter : IEventPublisher<BitmapSource>
    {
        IObservable<BitmapSource> IEventPublisher<BitmapSource>.EventObservable { get { return _bitmapImageSubject; } }
        private Subject<BitmapSource> _bitmapImageSubject;

        private IEventPublisher<ImageFrame> _imageFramePublisher;
        private int _frameRateMilliseconds;

        public ImageFrameToBitmapSourceConverter(IEventPublisher<ImageFrame> imageFramePublisher, int frameRateMilliseconds)
        {
            _imageFramePublisher = imageFramePublisher;
            _frameRateMilliseconds = frameRateMilliseconds;
            SetupBitmapImageObserver();
        }

        private void SetupBitmapImageObserver()
        {
            _bitmapImageSubject = new Subject<BitmapSource>();
            _imageFramePublisher
                .EventObservable
                .Sample(TimeSpan.FromMilliseconds(_frameRateMilliseconds))
                .ObserveOnDispatcher()
                .Subscribe(ConvertImageToBitmap);
        }

        public void ConvertImageToBitmap(ImageFrame imageFrame)
        {
            PlanarImage imageData = imageFrame.Image;
            var bitmapSource = BitmapSource.Create(imageData.Width, imageData.Height, 96, 96,
                 PixelFormats.Bgr32, null, imageData.Bits, imageData.Width * imageData.BytesPerPixel);
            _bitmapImageSubject.OnNext(bitmapSource);
        }
    }
}
